﻿using System;


namespace Sencha.Serialization.Bson.Serializers
{
	public class BsonUndefinedSerializer : TypeSerializer<BsonUndefined>
	{
		public override BsonUndefined Deserialize(IJsonReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			if (reader is IBsonReader)
				return this.DeserializeBson(reader as IBsonReader);

			if (reader.Token == JsonToken.Null)
				return null;

			var undefined = reader.ReadString(false);
			if (undefined != "undefined")
				throw new System.Runtime.Serialization.SerializationException("Undefined value expected");

			return BsonUndefined.Value;
		}
		private BsonUndefined DeserializeBson(IBsonReader reader)
		{
			if (reader.Token != BsonToken.Undefined)
				throw new Exceptions.UnexpectedBsonToken(reader, BsonToken.Undefined);

			return BsonUndefined.Value;
		}
		public override void Serialize(IJsonWriter writer, BsonUndefined value)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");

			if (value == null)
			{
				writer.WriteNull();
				return;
			}

			if (writer is IBsonWriter)
			{
				this.SerializeBson(writer as IBsonWriter, value);
				return;
			}

			writer.WriteJson("undefined");
		}
		private void SerializeBson(IBsonWriter writer, BsonUndefined value)
		{
			writer.Write(BsonToken.Undefined, (object)null);
		}
	}
}
